package com.ruoyi.system.exception;

import com.ruoyi.common.core.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName: GlobalExceptionHandler
 * @Description TODO
 * @Author: lingzhi
 * @Description:
 * @Date: Created in  2023/12/27  8:59
 */
@ControllerAdvice
@ResponseBody
@RefreshScope
public class GlobalExceptionHandler {


    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    //拦截什么异常
    @ExceptionHandler(value=Throwable.class)//拦截所有的异常
    public AjaxResult exceptionHandler(HttpServletRequest request, Throwable e){
        //    e.printStackTrace();
        /*全局异常处理*/
        if(e instanceof GlobalSysException) {
            GlobalSysException ex=(GlobalSysException) e;
            //	CodeMsg cm=ex.getCm();

           return AjaxResult.error(500,"GlobalException异常:"+ex.getMessage()  );

        }

        if(e instanceof BindException) { //是绑定异常的情况
            //强转
            BindException ex=(BindException) e;
            //获取错误信息
            List<ObjectError> errors=ex.getAllErrors();
            ObjectError error=errors.get(0);
            String msg=error.getDefaultMessage();

            // 记录日志
            logger.error("BindException error:"+ msg);

            return AjaxResult.error(500,"BindException error:"+msg  );

        }else {  //不是绑定异常的情况
            // 记录日志
            logger.error("Exception error:"+ e.getMessage() );
            return AjaxResult.error(500,e.getMessage()  );
        }
    }

}